import pygame
from datetime import datetime
from pygame.sprite import Sprite 
from .eventCenter import EventCenter
from pygame.sprite import Group


class Bullet(Sprite):
    ''' 子弹 '''
    def __init__(self,screen, x=0, y=0):
        super().__init__()

        self.screen = screen
        self.img = pygame.image.load('static/zd.png')
        self.rect = self.img.get_rect()

        self.rect.centery = y
        self.rect.left = x + 30
        self.speed = 20
        self.x = float(self.rect.left)
        self.createTime = datetime.now()
    
    def update(self):
        ''' 子弹移动 '''
        self.x += self.speed
        self.rect.left = self.x

    def blitme(self):
        self.screen.blit(self.img, self.rect)


class BulletFactory(EventCenter):
    
    def __init__(self, screen):
        
        self.screen = screen
        self.__bullets = Group()
        self.bindEvent()
        self.bullets = self.__bullets 
        self.registered('gameUpdate', self.update)
        self.registered('gameBlit', self.blitme)

    def bindEvent(self):
        self.registered('shoot', self.shoot)


    def shoot(self, data):
        self.createBullet(data["x"], data["y"])


    def createBullet(self, x, y):
        self.__bullets.add(Bullet(self.screen, x, y))


    def blitme(self, event):
        for item in self.__bullets:
            item.blitme()


    def update(self, event):
        
        self.bulletBoundary()

        for item in self.__bullets:
            item.update()
    
    
    def bulletBoundary(self):
        
        invalidBullet = []
        for item in self.__bullets:
            t = (datetime.now() - item.createTime).seconds

            if t > 0.4:
                invalidBullet.append(item)

        for item in invalidBullet:
            self.__bullets.remove(item)
